/*
 * 
 * 
 * 
 */
package com.cms.controller.admin;

import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import com.cms.constant.CommonConstant;
import com.cms.entity.Admin;
import com.cms.entity.Site;
import com.cms.service.SiteService;
import com.cms.utils.WebUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import java.text.ParseException;

import java.util.*;

/**
 * Controller - 首页
 * 
 * 
 * 
 */
@Controller("adminIndexController")
@RequestMapping("/admin/index")
public class IndexController extends BaseController {

	@Autowired
	private SiteService siteService;

	/**
	 * 首页
	 */
	@RequestMapping
	public String index(Integer siteId, ModelMap modelMap) {
		//站点
	    if(siteId == null){
	    	Admin currentAdmin = getCurrentAdmin();
	    	if(BooleanUtils.isFalse(currentAdmin.getRole().getIsSystem())
	    			&& CollectionUtils.isEmpty(currentAdmin.getRole().getSiteIds())){
				return "<script>alert('用户没有授权站点');history.back();</script>";
	    	}
	        Site defaultSite = siteService.findDefault();
	        if(BooleanUtils.isTrue(currentAdmin.getRole().getIsSystem())
	        		|| currentAdmin.getRole().getSiteIds().contains(defaultSite.getId())){
	        	siteId = defaultSite.getId();
	        }else{
	        	siteId = currentAdmin.getRole().getSiteIds().get(0);
	        }
	    }
    	Site currentSite = siteService.getById(siteId);
    	WebUtils.getSession().setAttribute(CommonConstant.ADMIN_SESSION_SITE, currentSite);
	    //统计
		modelMap.addAttribute("contentCount", SqlRunner.db().selectCount("select count(*) from cms_content"));
		modelMap.addAttribute("divCount", SqlRunner.db().selectCount("select count(*) from cms_div"));
		modelMap.addAttribute("guestbookCount", SqlRunner.db().selectCount("select count(*) from cms_guestbook"));
		modelMap.addAttribute("siteCount", SqlRunner.db().selectCount("select count(*) from cms_site"));
		String guestbookItemSql = "";
		String contentItemSql = "";
		for(int i=0;i<=6;i++){
			Date date = DateUtils.addDays(new Date(), -i);
			if(i>0){
				guestbookItemSql+=",";
				contentItemSql+=",";
			}
			guestbookItemSql += "(select count(*) from cms_guestbook where createDate <= '"+DateFormatUtils.format(date, "yyyy-MM-dd")+" 23:59:59') as '"+DateFormatUtils.format(date, "yyyy-MM-dd")+"'";
			contentItemSql += "(select count(*) from cms_content where createDate <= '"+DateFormatUtils.format(date, "yyyy-MM-dd")+" 23:59:59') as '"+DateFormatUtils.format(date, "yyyy-MM-dd")+"'";
		}
		String guestbookSql = "select "+guestbookItemSql;
		Map<String,Object> guestbookRecord = SqlRunner.db().selectOne(guestbookSql);
		List<String> guestbookColumnNames = new ArrayList<>(guestbookRecord.keySet());
		Collections.sort(guestbookColumnNames, new Comparator<String>() {
			@Override
			public int compare(String o1, String o2) {
				try {
					long o1Time = DateUtils.parseDate(o1,new String[]{"yyyy-MM-dd"}).getTime();
					long o2Time = DateUtils.parseDate(o2,new String[]{"yyyy-MM-dd"}).getTime();
					return o1Time-o2Time>0l?1:-1;
				} catch (ParseException e) {
					e.printStackTrace();
				}
				return 0;
			}
		});
		List<String> guestbookColumnValues = new ArrayList<>();
		for(String guestbookColumnName : guestbookColumnNames){
			guestbookColumnValues.add(guestbookRecord.get(guestbookColumnName).toString());
		}
		modelMap.addAttribute("guestbookTime", "'"+StringUtils.join(guestbookColumnNames,"','")+"'");
		modelMap.addAttribute("guestbookValue", StringUtils.join(guestbookColumnValues,","));

		String contentSql = "select "+contentItemSql;
		Map<String,Object> contentRecord = SqlRunner.db().selectOne(contentSql);
		List<String> contentColumnNames = new ArrayList<>(contentRecord.keySet());
		Collections.sort(contentColumnNames, new Comparator<String>() {
			@Override
			public int compare(String o1, String o2) {
				try {
					long o1Time = DateUtils.parseDate(o1,new String[]{"yyyy-MM-dd"}).getTime();
					long o2Time = DateUtils.parseDate(o2,new String[]{"yyyy-MM-dd"}).getTime();
					return o1Time-o2Time>0l?1:-1;
				} catch (ParseException e) {
					e.printStackTrace();
				}
				return 0;
			}
		});
		List<String> contentColumnValues = new ArrayList<>();
		for(String contentColumnName : contentColumnNames){
			contentColumnValues.add(contentRecord.get(contentColumnName).toString());
		}
		modelMap.addAttribute("contentTime", "'"+StringUtils.join(contentColumnNames,"','")+"'");
		modelMap.addAttribute("contentValue", StringUtils.join(contentColumnValues,","));
		
		return getView("index/index");
	}
}